package com.tanhua.admin.service;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.admin.mapper.SummaryMapper;
import com.tanhua.dubbo.api.SummaryApi;
import com.tanhua.model.db.Analysis;
import com.tanhua.model.db.Summary;
import com.tanhua.model.db.Year;
import com.tanhua.model.vo.YearVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SummaryService {

    @DubboReference
    private SummaryApi summaryApi;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private SummaryMapper summaryMapper;//日统计表

    @Autowired
    private AnalysisMapper analysisMapper;  //概要表

    //概要统计
    public Summary sum(){
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        String lastWeek = DateUtil.lastWeek().toString("yyyy-MM-dd");
        String lastMonth = DateUtil.lastMonth().toString("yyyy-MM-dd");

        //1.累计用户查询  注册的总人数
        Integer count = analysisMapper.count();

        //2.过去7天、30天活跃用户
        Integer activeWeekNum = analysisMapper.querySevenUsers();
        Integer activeMonthNum = analysisMapper.queryMonthUsers();
        //3.新增用户(今日注册的人数)
        Integer regNum = analysisMapper.queryRes(today);
        if (regNum == null) {
            regNum = 0;
        }
        //3.1今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        Integer regYesNum = analysisMapper.queryRes(yesterday);
        if (regYesNum == null) {
            regYesNum = 0;
        }
        Integer regPercentage ;
        if (regYesNum != 0){
            Double a = ((regNum - regYesNum)*1.0/regYesNum)*100;
            regPercentage = a.intValue();
        }else{
            regPercentage = regNum*100;
        }
        //4.登录次数(今日)
        Integer logNum = analysisMapper.queryLogin(today);
        //4.1今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        Integer logYesNum = analysisMapper.queryLogin(yesterday);
        if (logYesNum == null) {
            logYesNum = 0;
        }
        if (logNum == null) {
            logNum = 0;
        }
        Integer logPercentage = null;

        if (logYesNum != 0){
            //logPercentage = ((logNum - logYesNum)/logYesNum)*100;
            Double b = ((logNum - logYesNum)*1.0/logYesNum)*100;
            logPercentage = b.intValue();
        }else{
            logPercentage = logNum*100;
        }

        //5.活跃用户(今日)
        Integer activeNum = analysisMapper.queryActive(today);
        Integer activeYesNum = analysisMapper.queryActive(yesterday);
        if (activeNum == null) {
            activeNum = 0;
        }
        if (activeYesNum == null) {
            activeYesNum = 0;
        }
        //5.1今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        Integer activeUsersPercentage = null;
        if (activeYesNum != 0){
            //activeUsersPercentage = Integer.valueOf(((activeNum - activeYesNum)*1.0/activeYesNum)*100+"");
            Double c = ((activeNum - activeYesNum)*1.0/activeYesNum)*100;
            activeUsersPercentage = c.intValue();
        }else{
            activeUsersPercentage = activeNum*100;
        }
        Summary summary = null;



        //6.根据当前日志，查询统计表
        try {
            QueryWrapper<Analysis> qw = new QueryWrapper<>();
            Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(today); //年月日
            qw.eq("record_date",recordDate);
            Analysis analysis = analysisMapper.selectOne(qw);
            //2.1 如果数据不存在，保存统计数据
            if(analysis == null) {
                analysis = new Analysis();
                analysis.setRecordDate(recordDate);
                analysis.setNumRegistered(regNum);
                analysis.setNumActive(activeNum);
                analysis.setNumLogin(logNum);
                analysisMapper.insert(analysis);
            }else {
                //2.2 数据存在，更新统计数据
                analysis.setNumRegistered(regNum);
                analysis.setNumActive(activeNum);
                analysis.setNumLogin(logNum);
                analysisMapper.updateById(analysis);
            }
        }catch (ParseException e) {
            e.printStackTrace();
        }
        summary = new Summary();
        //累计用户
        summary.setCumulativeUsers(count);
        //过去30天活跃用户
        summary.setActivePassMonth(activeMonthNum);
        //过去7天活跃用户
        summary.setActivePassWeek(activeWeekNum);
        //今日新增用户
        summary.setNewUsersToday(regNum);
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        summary.setNewUsersTodayRate(regPercentage);
        //今日登录次数
        summary.setLoginTimesToday(logNum);
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        summary.setLoginTimesTodayRate(logPercentage);
        //今日活跃用户
        summary.setActiveUsersToday(activeNum);
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        summary.setActiveUsersTodayRate(activeUsersPercentage);
        return summary;
    }

    //新增、活跃用户、次日留存率
    public YearVo users(Long sd, Long ed, Integer type) {
//        String sdate = new SimpleDateFormat("yyyy-MM-dd").format(sd);
//        String edate = new SimpleDateFormat("yyyy-MM-dd").format(ed);

        //101 新增 102 活跃用户 103 次日留存率
        Long time = ed - sd;
        Long l = time / 86400000l;
        System.out.println("===天数l===="+l);
        if (type == 101){
            return methodRes(l, sd);
        }else if (type == 102){
            return methodActive(l, sd);
        }else {
        }
        return null;
    }


/*        if (type == 101){
            //新增
            Integer amountResUsers = analysisMapper.queryResUsers(sd, ed);
            for (int i = 1; i < 13; i++) {
                Year year1 = yearCreated(i, DateUtil.year(new Date()));
                Year year2 = yearCreated(i, DateUtil.thisYear() - 1);
                thisYear[i] = year1;
                lastYear[i] = year2;
            }
        }else if (type == 102){
            //活跃用户
            Integer amountActive = analysisMapper.queryActiveUsers(sd, ed);
            for (int i = 1; i < 13; i++) {
                Year year1 = yearCreated(i, DateUtil.year(new Date()));
                Year year2 = yearCreated(i, DateUtil.thisYear() - 1);
                thisYear[i] = year1;
                lastYear[i] = year2;
            }
        }else {
            //次日留存率
            Integer amountRetent = logMapper.queryNumRetentionId(ed, sd);
            for (int i = 1; i < 13; i++) {
                Year year1 = yearCreated(i, DateUtil.year(new Date()));
                Year year2 = yearCreated(i, DateUtil.thisYear() - 1);
                thisYear[i] = year1;
                lastYear[i] = year2;
            }
        }*/


    public YearVo methodRes(Long l,Long sd){
        //Year[] thisYear = new Year[b];
        List<Year> thisYear = new ArrayList<>();
        //Year[] lastYear = new Year[b];
        List<Year> lastYear = new ArrayList<>();

        for (Long i = 0l; i <= l; i++) {
            System.out.println("=======循环次数======="+i);
            //根据时间查询
            Long aaa = sd + (i * 86400000l);
            System.out.println("当前时间是" + aaa+"========");
            String bbb = new SimpleDateFormat("yyyy-MM-dd").format(aaa);
            System.out.println("格式化之后的时间" + bbb+"========");
            Integer thisAmount = analysisMapper.findRes(bbb);
            Year thisY = new Year();
            if (thisAmount == null){
                thisAmount = 0;
            }
            thisY.setTitle((i+1)+"");
            thisY.setAmount(thisAmount);
            thisYear.add(thisY);
            System.out.println(thisY);
        }
        //Year year = new Year();
        for (Long i = 0l; i <= l; i++) {

            Integer lastAmount = analysisMapper.findRes(new SimpleDateFormat("yyyy-MM-dd").format(sd + ((i-365) * 86400000)));
            if (lastAmount == null){
                lastAmount = 0;
            }
            Year lastY = new Year();
            lastY.setAmount(lastAmount);
            lastY.setTitle((i+1)+"");
            lastYear.add(lastY);
        }
        System.out.println(thisYear);
        YearVo yearVo = new YearVo(lastYear,thisYear);
        return yearVo;
    }

    public YearVo methodActive(Long l,Long sd){
        //Year[] thisYear = new Year[b];
        List<Year> thisYear = new ArrayList<>();
        //Year[] lastYear = new Year[b];
        List<Year> lastYear = new ArrayList<>();
        //Year year = new Year();
        for (Long i = 0l; i <= l; i++) {
            System.out.println(i);
            //根据时间查询
            Integer thisAmount = analysisMapper.findActive(new SimpleDateFormat("yyyy-MM-dd").format(sd + (i * 86400000)));
            if (thisAmount == null){
                thisAmount = 0;
            }
            Year thisY = new Year();
            thisY.setAmount(thisAmount);
            thisY.setTitle((i+1)+"");
            thisYear.add(thisY);

            Integer lastAmount = analysisMapper.findActive(new SimpleDateFormat("yyyy-MM-dd").format(sd + ((i-365) * 86400000)));

            if (lastAmount == null){
                lastAmount = 0;
            }
            Year lastY = new Year();
            lastY.setAmount(lastAmount);
            lastY.setTitle((i+1)+"");
            lastYear.add(lastY);
        }
        YearVo yearVo = new YearVo(lastYear,thisYear);
        return yearVo;
    }

    /*public YearVo methodRetent(Long ed,Long sd,String kind){
        //次日留存率
        Integer amountRetent = logMapper.queryNumRetentionId(ed, sd);


        //YearVo yearVo = new YearVo(thisYear, lastYear);
        return yearVo;
        }*/
}
